module regfile #(
  parameter N_REGS = 32
) (
  input clk,
  input rst_n,
  input      [$clog2(N_REGS)-1:0] rs1,
  input      [$clog2(N_REGS)-1:0] rs2,
  input                           ctrl_id_stall,
  input                           rs1_bypass_en,
  input      [31:0]               rs1_bypass_data,
  input                           rs2_bypass_en,
  input      [31:0]               rs2_bypass_data,
  output reg [31:0]               rs1_data,
  output reg [31:0]               rs2_data,
  input                           rd_wena,
  input      [$clog2(N_REGS)-1:0] rd,
  input      [31:0]               rd_data
);

  reg [31:0] registers [1:N_REGS-1];

  always @(posedge clk, negedge rst_n) begin
    if (~rst_n) begin
      rs1_data <= 32'b0;
    end else if (~ctrl_id_stall) begin
      if (rs1 == 'h0) begin
        rs1_data <= 32'b0;
      end else if (rs1_bypass_en) begin
        rs1_data <= rs1_bypass_data;
      end else if (rd_wena && rs1 == rd) begin
        rs1_data <= rd_data;
      end else begin
        rs1_data <= registers[rs1];
      end
    end
  end

  always @(posedge clk, negedge rst_n) begin
    if (~rst_n) begin
      rs2_data <= 32'b0;
    end else if (~ctrl_id_stall) begin
      if (rs2 == 'h0) begin
        rs2_data <= 32'b0;
      end else if (rs2_bypass_en) begin
        rs2_data <= rs2_bypass_data;
      end else if (rd_wena && rs2 == rd) begin
        rs2_data <= rd_data;
      end else begin
        rs2_data <= registers[rs2];
      end
    end
  end

  integer i;
  always @(posedge clk, negedge rst_n) begin
    if (~rst_n) begin: reset_registers
      for (i = 1; i < N_REGS; i = i + 1) begin
        registers[i] <= 'h0;
      end
    end
    else if (rd_wena && rd != 0) begin
      registers[rd] <= rd_data;
    end
  end



endmodule

